<template>

  <div class="article-list">
  <van-pull-refresh v-model="refreshing"   :success-text="shuxin" @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
  error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
     <ArticleItem
     v-for="(va,index) in list" :key="index"

     :article='va'
     />
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { tuijian } from '@/api/user'
import ArticleItem from '../../../components/article-item/index.vue'
export default {
  name: 'ArticleList',
  components: {

    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      timestamp: null, // 请求下一页数据的时间戳
      error: false,
      refreshing: false,
      shuxin: '刷新成功'
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    // 初始化或滚动到底部的时候会触发调用 onLoad
    async onLoad () {
    //  console.log(this.channel);
      try {
        //  1首次加载
        const { data } = await tuijian({
          channel_id: this.channel.id,
          //   用时间戳控制页码
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // console.log(data.data.results);
        this.list.push(...data.data.results)
        this.loading = false
        // 4. 判断数据是否全部加载完成：（如果长度为0说明没有数据）
        if (data.data.results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
          this.finished = true// (显示没有更多)
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const { data } = await tuijian({
          channel_id: this.channel.id,
          //   用时间戳控制页码
          timestamp: Date.now(),
          with_top: 1
        })
        this.list.unshift(...data.data.results)

        this.refreshing = false
      } catch (error) {
        this.shuxin = '刷新失败'
        this.refreshing = false
      }

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    }
  }
}
</script>

<style scoped lang="less">
.article-list{height:79vh;
overflow-y: auto;
}
</style>
